package com.ffcc.fitness.like.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.ffcc.fitness.base.response.JsonResult;
import com.ffcc.fitness.base.response.StatusCode;
import com.ffcc.fitness.like.pojo.dto.LikeDTO;
import com.ffcc.fitness.like.pojo.vo.LikeVO;
import com.ffcc.fitness.like.service.LikeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 点赞控制器
 */
@Slf4j
@RestController
@RequestMapping("/v1/like/")
public class LikeController {
    
    @Autowired
    private LikeService likeService;
      /**
     * 切换点赞状态（点赞或取消点赞）
     */
    @PostMapping("toggle")
    public JsonResult toggleLike(@RequestBody LikeDTO likeDTO) {
        log.info("切换点赞状态请求：{}", likeDTO);
        
        try {
            // 验证参数
            if (likeDTO.getTargetId() == null || likeDTO.getTargetType() == null) {
                return new JsonResult(StatusCode.PARAMETER_ERROR, "目标ID和目标类型不能为空");
            }
            
            // 设置当前登录用户ID
            if (StpUtil.isLogin()) {
                likeDTO.setUserId(StpUtil.getLoginIdAsLong());
            } else {
                return new JsonResult(StatusCode.NOT_LOGIN, "请先登录");
            }
            
            // 执行点赞切换
            likeService.toggleLike(likeDTO);
            
            // 获取更新后的点赞信息返回给前端
            LikeVO likeVO = likeService.getLikeInfo(likeDTO.getUserId(), likeDTO.getTargetId(), likeDTO.getTargetType());
            return JsonResult.ok(likeVO);
            
        } catch (RuntimeException e) {
            log.error("切换点赞状态失败：{}", e.getMessage());
            return new JsonResult(StatusCode.OPERATION_FAILED, e.getMessage());
        } catch (Exception e) {
            log.error("切换点赞状态异常", e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "操作失败");
        }
    }
    
    /**
     * 获取点赞信息（点赞数量和当前用户点赞状态）
     */
    @SaIgnore
    @GetMapping("info")
    public JsonResult getLikeInfo(@RequestParam Long targetId, 
                                 @RequestParam Integer targetType) {
        log.info("获取点赞信息：targetId={}，targetType={}", targetId, targetType);
        
        try {
            // 验证参数
            if (targetId == null || targetType == null) {
                return new JsonResult(StatusCode.PARAMETER_ERROR, "目标ID和目标类型不能为空");
            }
            
            // 获取当前用户ID（如果已登录）
            Long userId = null;
            if (StpUtil.isLogin()) {
                userId = StpUtil.getLoginIdAsLong();
            }
            
            LikeVO likeVO = likeService.getLikeInfo(userId, targetId, targetType);
            return JsonResult.ok(likeVO);
            
        } catch (RuntimeException e) {
            log.error("获取点赞信息失败：{}", e.getMessage());
            return new JsonResult(StatusCode.OPERATION_FAILED, e.getMessage());
        } catch (Exception e) {
            log.error("获取点赞信息异常", e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询失败");
        }
    }
    
    /**
     * 获取目标的点赞数量
     */
    @SaIgnore
    @GetMapping("count")
    public JsonResult getLikeCount(@RequestParam Long targetId,
                                  @RequestParam Integer targetType) {
        log.info("获取点赞数量：targetId={}，targetType={}", targetId, targetType);
        
        try {
            // 验证参数
            if (targetId == null || targetType == null) {
                return new JsonResult(StatusCode.PARAMETER_ERROR, "目标ID和目标类型不能为空");
            }
            
            Long count = likeService.getLikeCount(targetId, targetType);
            return JsonResult.ok(count);
            
        } catch (RuntimeException e) {
            log.error("获取点赞数量失败：{}", e.getMessage());
            return new JsonResult(StatusCode.OPERATION_FAILED, e.getMessage());
        } catch (Exception e) {
            log.error("获取点赞数量异常", e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询失败");
        }
    }
    
    /**
     * 检查用户是否已点赞
     */
    @GetMapping("check")
    public JsonResult checkIsLiked(@RequestParam Long targetId,
                                  @RequestParam Integer targetType) {
        log.info("检查点赞状态：targetId={}，targetType={}", targetId, targetType);
        
        try {
            // 验证参数
            if (targetId == null || targetType == null) {
                return new JsonResult(StatusCode.PARAMETER_ERROR, "目标ID和目标类型不能为空");
            }
            
            // 检查是否登录
            if (!StpUtil.isLogin()) {
                return JsonResult.ok(false);
            }
            
            Long userId = StpUtil.getLoginIdAsLong();
            Boolean isLiked = likeService.isLiked(userId, targetId, targetType);
            return JsonResult.ok(isLiked);
            
        } catch (RuntimeException e) {
            log.error("检查点赞状态失败：{}", e.getMessage());
            return new JsonResult(StatusCode.OPERATION_FAILED, e.getMessage());
        } catch (Exception e) {
            log.error("检查点赞状态异常", e);
            return new JsonResult(StatusCode.OPERATION_FAILED, "查询失败");
        }
    }
}